from django.core.urlresolvers import reverse
from django.utils import feedgenerator
from django.shortcuts import *
from django.template import RequestContext 
from django.utils.simplejson import *
from ytbase.helper import *
from ytbase.model.post import *
from ytbase.model.auth import *
from ytcommunity.forum.setting import CATEGORY, POST_NUM_PER_PAGE, CONFIG, RECENT_POST_NUM
from ytcommunity.forum.helper.context import *
from ytcommunity.forum.model.board import *
import ytbase.view.post

def add(request, name, template):
    board = YTBoard.get_by_name(name)
    
    def filler(post):
        post.category = CATEGORY
        post.ref = board
        board.number += 1
        board.put()
        return post
    
    def add_board(request):
        context = {}
        context['board'] = board
        return context        
    
    return ytbase.view.post.add(request, template=template, 
        filler = filler,
        redirect_helper=get_url, 
        processors=PROCESSORS+[add_board])

def edit(request, id, template):
    return ytbase.view.post.edit(request, id=id, template=template, 
        redirect_helper=get_url, 
        processors=PROCESSORS)

def display(request, id, template):
    
    def add_board_path(request):
        post = get_by_str_id(YTPost, id)
        context = {}
        context['board'] = post.ref
        return context    
    
    return ytbase.view.post.display(request, id=id, template=template,
        processors = PROCESSORS+[add_board_path])
    
def _list_internal(request, num_per_page=POST_NUM_PER_PAGE):
    filters = []
    filters.append(lambda q: q.filter('category =', CATEGORY))
    filters.append(lambda q: q.order('-update'))
    posts, page = Paginator(request, YTPost, filters, num_per_page).get_page_objects()
    
    context = {
        'posts': posts,
        'page': page,
    }    
    return context

def all(request, template, num_per_page=POST_NUM_PER_PAGE):
    context = _list_internal(request, num_per_page)
    rc = RequestContext(request, processors=PROCESSORS)
    return render_to_response(template, context, rc)

@check_page_cache(True)
def latest(request, template):
    return all(request, template, RECENT_POST_NUM)

@check_page_cache(True)
def query_api(request):
    context = _list_internal(request, RECENT_POST_NUM)
    
    from django.utils.html import escape
    def transfer(post):
        return {
            'title': escape(post.title),
            'id': post.key().id(),
            'url': get_url(post)
            }
    
    context['posts'] = [transfer(post) for post in context['posts']]
    json = dumps(context)
    return HttpResponse(json, mimetype="application/json")    

def feed(request, name='', title=CONFIG['site_title'], descr=CONFIG['site_description']):
    filters = []

    if name:
        board = YTBoard.get_by_name(name)
        filters.append(lambda q: q.filter('ref =', board.key()))
        title = board.title + ' - ' + title

    filters.append(lambda q: q.filter('category =', CATEGORY))
    filters.append(lambda q: q.order('-update'))
    posts, page = Paginator(request, YTPost, filters, POST_NUM_PER_PAGE).get_page_objects()
    
    f = feedgenerator.Rss201rev2Feed(title=title, link=request.host_url, description=descr)
    for post in posts:
        f.add_item(
            title=post.title, 
            link=request.host_url+get_url(post), 
            description=post.content,
            author_name=post.author.get_name(),
            pubdate=post.update)
        
    return HttpResponse(f.writeString('UTF-8') , mimetype="application/rss+xml")

@check_id(YTPost)
@authorize(YTPost, OPERATION_DELETE)
def delete(request, id):
    if request.method == 'POST':
        post = get_by_str_id(YTPost, id)
        board = post.ref
        board.number -= 1
        board.put()
        post.delete()
        return HttpResponse('Deleted!')        
    return HttpResponseNotFound()

@check_id(YTPost)
@authorize_admin
def stick(request, id):
    if request.method == 'POST':
        post = get_by_str_id(YTPost, id)
        post.hot = True
        post.put()
        return HttpResponse('Done!')        
    return HttpResponseNotFound()

@check_id(YTPost)
@authorize_admin
def unstick(request, id):
    if request.method == 'POST':
        post = get_by_str_id(YTPost, id)
        post.hot = False
        post.put()
        return HttpResponse('Done!')        
    return HttpResponseNotFound()

def get_url(post):
    return reverse('ytcommunity.forum.view.post.display', kwargs={'id':str(post.key().id())})
